<template>
  <div class="content-detail">
    <el-card class="card-box" v-if="isShowBase">
      <template #header>
        <div class="card-box-header">
          <span>基础信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <!-- 材料验收审批接基本信息 -->
        <div v-show="show1">
          <flow-basic-info-material
            :basicInfoData="formBaseInfo"
            :module="module"
            :billNum="billNum"
            v-if="['material', 'conceal', 'witness', 'snap'].includes(module)"
          />
          <InspectionInfo
            v-else-if="['inspection'].includes(module)"
            :disabled="true"
            :basicInfoData="formBaseInfo"
            :isShowBase="false"
          ></InspectionInfo>
          <VehicleBasicInfo
            v-else-if="['vehicle'].includes(module)"
            :disabled="true"
            :basicInfoData="formBaseInfo"
            :isShowBase="false"
          ></VehicleBasicInfo>
          <flow-basic-info
            :basicInfoData="formBaseInfo"
            :billNum="billNum"
            v-else
          />
        </div>
      </el-collapse-transition>
    </el-card>

    <el-card
      class="card-box"
      v-if="['material', 'conceal', 'witness', 'snap'].includes(module)"
    >
      <template #header>
        <div class="card-box-header">
          <span>检查/检验信息</span>
          <div v-if="show8" @click="show8 = !show8" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show8 = !show8" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <!-- 材料验收/隐蔽验收审批接基本信息 -->
        <div v-show="show8">
          <check-basic-info :basicInfoData="formBaseInfo" />
        </div>
      </el-collapse-transition>
    </el-card>

    <el-card class="card-box" v-if="['vehicle'].includes(module)">
      <template #header>
        <div class="card-box-header">
          <span>物资内容</span>
          <div v-if="show8" @click="show8 = !show8" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show8 = !show8" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="show8">
          <vehicle-material-info :basicInfoData="formBaseInfo" />
        </div>
      </el-collapse-transition>
    </el-card>

    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流程状态</span>
          <div v-if="show4" @click="show4 = !show4" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show4 = !show4" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <status-info
          :currentStep="currentStep"
          :steps="steps"
          :isChargehand="isChargehand"
          jumpStep="副厂长"
          v-show="show4"
        />
      </el-collapse-transition>
    </el-card>

    <el-card
      class="card-box"
      v-if="
        nodeDefId !== 'ACT_010' &&
        module !== 'material' &&
        module !== 'conceal' &&
        module !== 'witness' &&
        module !== 'snap' &&
        module !== 'inspection' &&
        module !== 'vehicle'
      "
    >
      <template #header>
        <div class="card-box-header">
          <span>审批内容</span>
          <div v-if="show7" @click="show7 = !show7" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show7 = !show7" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>

      <el-form
        :model="flowFormData"
        label-width="140px"
        class="form__content content-box"
      >
        <el-form-item label="审批内容">
          <div
            v-html="flowFormData.approvalForm"
            class="read-content tinymce-box"
          ></div>
        </el-form-item>

        <el-form-item label="附件">
          <p
            class="text--info download-link subtext"
            v-for="(item, index) in defaultFileList"
            :key="index"
            @click="handlePreview(item)"
          >
            <el-link :underline="false">{{ item?.name }}</el-link>
          </p>
          <p
            class="text--info download-link subtext fs12"
            v-if="!defaultFileList || defaultFileList.length === 0"
          >
            -
          </p>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card
      class="card-box"
      v-if="isEdit && nodeDefId.toLocaleUpperCase() !== 'END'"
    >
      <template #header>
        <div class="card-box-header">
          <span>待处理</span>
          <div v-if="show5" @click="show5 = !show5" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show5 = !show5" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>

      <el-collapse-transition>
        <div v-show="show5">
          <pending-material
            :formBaseInfo="formBaseInfo"
            v-if="module === 'material'"
            @handleBack="handleBack"
          />
          <pending-conceal
            :formBaseInfo="formBaseInfo"
            :module="module"
            v-else-if="module === 'conceal' || module === 'witness'"
            @handleBack="handleBack"
          />
          <pending-snap
            :formBaseInfo="formBaseInfo"
            :module="module"
            v-else-if="module === 'snap'"
            @handleBack="handleBack"
          />
          <pending-inspection
            :formBaseInfo="formBaseInfo"
            :module="module"
            v-else-if="module === 'inspection'"
            @handleBack="handleBack"
          />
          <pending-vehicle
            :formBaseInfo="formBaseInfo"
            :module="module"
            v-else-if="module === 'vehicle'"
            @handleBack="handleBack"
          />
          <template v-else>
            <div v-show="show5" class="content-box">
              <el-form
                :model="flowFormData"
                :rules="fromRules"
                ref="flowFormRef"
                label-width="140px"
                class="form__content"
              >
                <template v-if="nodeDefId === 'ACT_010' && isEdit">
                  <el-form-item label="审批内容">
                    <div class="tinymce-box">
                      <re-edit v-model="flowFormData.approvalForm"></re-edit>
                    </div>
                  </el-form-item>

                  <el-form-item label="附件上传">
                    <ecm-upload
                      :files="defaultFileList"
                      @set-file="
                        fileList => {
                          handleChange(fileList);
                        }
                      "
                    ></ecm-upload>
                  </el-form-item>
                </template>

                <!-- <template v-else>
                  <el-form-item label="审批内容">
                    <div
                      v-html="flowFormData.approvalForm"
                      class="read-content tinymce-box"
                    ></div>
                  </el-form-item>

                  <el-form-item label="附件">
                    <p
                      class="text--info download-link subtext"
                      v-for="(item, index) in defaultFileList"
                      :key="index"
                      @click="handlePreview(item)"
                    >
                      <el-link :underline="false">{{ item?.name }}</el-link>
                    </p>
                    <p
                      class="text--info download-link subtext fs12"
                      v-if="!defaultFileList || defaultFileList.length === 0"
                    >
                      -
                    </p>
                  </el-form-item>
                </template> -->
                <el-form-item
                  label="审批意见"
                  prop="approvalComments"
                  v-if="nodeDefId !== 'ACT_010'"
                >
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入审批意见"
                    v-model="flowFormData.approvalComments"
                  ></el-input>
                </el-form-item>

                <el-form-item label="备注">
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入备注"
                    v-model="flowFormData.remarks"
                  ></el-input>
                </el-form-item>
              </el-form>

              <div class="form__footer right-align-box" v-if="isEdit">
                <el-button @click="handleBack">取消</el-button>
                <!-- <el-button type="primary" @click="handleSave">保 存</el-button> -->
                <el-button
                  type="primary"
                  @click="handleTransfer"
                  v-if="nodeDefId !== 'ACT_010'"
                  >转 办</el-button
                >
                <el-button
                  type="danger"
                  @click="handleSubmit('0')"
                  v-if="backNode && lastNode === nodeDefId"
                  >驳 回</el-button
                >
                <el-button
                  class="danger"
                  v-else-if="nodeDefId !== 'ACT_010'"
                  type="danger"
                  @click="handleReject"
                  >驳 回</el-button
                >
                <el-button type="primary" @click="inform"> 知 会</el-button>
                <el-button type="primary" @click="handleSave">保 存</el-button>
                <el-button type="primary" @click="handleSubmit('1')"
                  >提 交</el-button
                >
              </div>
            </div>
          </template>
        </div>
      </el-collapse-transition>
    </el-card>

    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流转记录</span>
          <div v-if="show6" @click="show6 = !show6" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show6 = !show6" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <flow-info
          v-show="show6"
          :instanceId="instanceIdFlow"
          :nodeDefId="nodeDefId"
        />
      </el-collapse-transition>
    </el-card>

    <el-dialog
      title="选择人员"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        @emitAddUser="showNextJump"
      />
    </el-dialog>

    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view
        v-model:dialogVisible="dialogVisible"
        :taskId="taskIdMain"
        :formBaseInfo="formBaseInfo"
      />
    </el-dialog>

    <el-dialog
      title="下一步流转至"
      v-model="dialogVisibleNext"
      destroy-on-close
      width="600px"
    >
      <div class="next-content">
        <el-radio-group
          v-if="nextJumpToArr && nextJumpToArr.length"
          v-model="nextJumpToId"
        >
          <el-radio
            v-for="item in nextJumpToArr"
            :key="item.id"
            :label="item.id"
            border
            @change="changeNextJump"
            >{{ item.name }}</el-radio
          >
        </el-radio-group>
      </div>

      <div class="form__footer">
        <el-button @click="dialogVisibleNext = false">取 消</el-button>
        <el-button type="primary" @click="handleNextJump">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 最后一步驳回到指定节点 -->
    <el-dialog
      title="驳回"
      v-model="dialogVisibleLastNode"
      destroy-on-close
      width="600px"
    >
      <el-form
        :model="rejectFormData"
        ref="rejectFormRef"
        :rules="rejectRules"
        label-position="top"
        label-width="80px"
        class="content"
      >
        <el-form-item label="驳回意见" prop="remark">
          <el-input
            v-model.trim="rejectFormData.remark"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row justify="end" class="form__footer">
        <el-button @click="dialogVisibleLastNode = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ProcessStatusEnum } from "../types";
import NotifMessage from "/@/utils/message/notification";
import StatusInfo from "../components/processInfo/StatusInfo.vue";
import FlowInfo from "../components/processInfo/FlowInfo.vue";
import FlowBasicInfo from "../components/processInfo/FlowBasicInfo.vue";
import CheckBasicInfo from "../components/processInfo/CheckBasicInfo.vue";
import FlowBasicInfoMaterial from "../components/processInfo/FlowBasicInfoMaterial.vue";
import VehicleBasicInfo from "../components/processInfo/VehicleBasicInfo.vue";
import VehicleMaterialInfo from "../components/processInfo/VehicleMaterialInfo.vue";
import PendingMaterial from "../components/processInfo/PendingMaterial.vue";
import PendingConceal from "../components/processInfo/PendingConceal.vue";
import PendingSnap from "../components/processInfo/PendingSnap.vue";
import PendingInspection from "../components/processInfo/PendingInspection.vue";
import PendingVehicle from "../components/processInfo/PendingVehicle.vue";
import InspectionInfo from "/@/views/projectsS/construction/inspection/index.vue";
import ReEdit from "/@/components/ReEditor/index.vue";
import AddUser from "../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import RejectView from "../components/dialog/RejectView.vue";
import ecmUpload from "/@/components/ecmUpload/index.vue";
import { flowNotify } from "/@/api/work";
import { handlePreview, onFilterFileData } from "/@/utils/file";
import { storageLocal } from "/@/utils/storage";
import { getTaskIdApi, getApproveHandlerId } from "/@/api/projects";
import {
  getFlowInfo,
  getInspectionInfo,
  flowStart,
  flowSubmit,
  // storageFlowdata,
  transfer,
  postSaveDraft,
  getDraft
} from "/@/api/projects";
import { flowNotifyRead } from "/@/api/work";
import {
  materialFlowInfo,
  concealFlowInfo,
  witnessFlowInfo,
  snapFlowInfo,
  civilizFlowInfo
} from "/@/api/construction";
import { getAccessFlowInfo } from "/@/api/vehicle";
// import { postGetStorageTmpData, postStorageTmpData } from "/@/api/acceptance";
import { flowTypeObj } from "./type";
import { clickEvent } from "/@/utils/func";
import { postApproveHistory } from "/@/api/acceptance";
const props = defineProps({
  instanceId: {
    type: Number,
    default: 0
  },
  flowId: {
    type: Number || String,
    default: ""
  },
  contractId: {
    type: Number,
    required: true,
    default: 0
  },
  nodeDefId: {
    type: String,
    required: true,
    default: "ACT_010"
  },
  isEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  isShowBase: {
    type: Boolean,
    required: true,
    default: true
  },
  module: {
    type: String,
    required: true,
    default: ""
  },
  flowType: {
    type: String,
    required: true,
    default: ""
  },
  readId: {
    type: String,
    default: ""
  },
  approvalType: {
    type: String,
    default: ""
  },
  taskId: {
    type: String,
    default: ""
  },
  source: {
    type: String,
    default: ""
  },
  billNum: {
    type: String,
    default: ""
  }
});
const router = useRouter();
const route = useRoute();
let currentStep = ref(ProcessStatusEnum.ACT_010);
const flowFormRef = ref<HTMLFormElement | null>(null) as any;
const rejectFormRef = ref<HTMLFormElement | null>(null) as any;
let currentNode = ref("");
let signNode = ref(""); //是否是会签节点
let steps = ref([]);
let nextJumpToArr = ref([]);
let nextJumpToId = ref("");
let formBaseInfo = ref<object>({}); // 基础信息
let addUserInfo = ref<object>({}); // 人员选择器，所选择人员信息
let flowFormData = ref({}); // 待处理信息
let taskIdMain = ref("");
let taskIdNotify = ref("");
let dialogVisibleTransferAdd = ref(false); // 选择人员的弹窗是否显示
let dialogVisibleType = ref("submit");
let dialogVisible = ref(false); // 驳回弹窗是否展示
let dialogVisibleNext = ref(false);
let acceptUsers = ref([]); // 已选择人员
let instanceIdFlow = ref(); // 实例ID
let flowType = ref(route.query?.flowType);
const nodeDefId = ref(route.query?.nodeDefId);
let instanceId = ref("");
instanceId.value = route.query?.instanceId || props.instanceId;
let userInfo = storageLocal.getItem("info");
const approveHandlerId = ref("");
const lastNode = ref("");
const backNode = ref("");
flowType.value = route.query?.flowType || props.flowType;
const nodeList = flowTypeObj[flowType.value].nodeId;
lastNode.value = nodeList[nodeList.length - 1];
console.log(lastNode.value);
backNode.value = flowTypeObj[flowType.value].backNode;
const rejectFormData = ref({
  remark: ""
});
const rejectRules = ref({
  remark: [{ required: true, message: "请输入驳回意见", trigger: "change" }]
});
const dialogVisibleLastNode = ref(false);
let show1 = ref(true);
let show4 = ref(true);
let show5 = ref(true);
let show6 = ref(true);
let show7 = ref(true);
let show8 = ref(true);
let defaultFileList = ref([]);

let isChargehand = ref("0");

const fromRules = ref({
  approvalComments: [
    { required: true, message: "请输入审批意见", trigger: "blur" }
  ]
});
// 进入详情进行判断节点位置
if (props.nodeDefId) {
  currentStep.value = ProcessStatusEnum[props.nodeDefId as string];
}

// 基础信息获取
const getInitFlowInfo = async () => {
  const { contractId } = props;
  if (!contractId) {
    return;
  }
  const params = {
    id: contractId
  };
  let apiFunctionName = getFlowInfo;
  const module = props.module;
  if (module) {
    switch (module) {
      case "material":
        apiFunctionName = materialFlowInfo;
        break;
      case "conceal":
        apiFunctionName = concealFlowInfo;
        break;
      case "witness":
        apiFunctionName = witnessFlowInfo;
        break;
      case "snap":
        apiFunctionName = snapFlowInfo;
        break;
      case "vehicle":
        apiFunctionName = getAccessFlowInfo;
        break;
      case "civiliz":
        apiFunctionName = civilizFlowInfo;
        break;
      case "inspection":
        apiFunctionName = getInspectionInfo;
      default:
        break;
    }
  }
  const { code, data } = await apiFunctionName(params);
  if (code === 200) {
    let flowFormDataList = data.flowFormDataList || [];
    let approvals =
      flowFormDataList.length && flowFormDataList[flowFormDataList.length - 1];
    if (props.module == "inspection") {
      formBaseInfo.value = data;
      const res2 = await getTaskIdApi({ instanceId: instanceId.value });
      if (res2.code == 200) {
        formBaseInfo.value.taskId = res2.data.taskId;
        taskIdMain.value = res2.data.taskId;
      }
    } else {
      formBaseInfo.value = data.formBaseInfo;
      taskIdMain.value = data.taskId;
      formBaseInfo.value.taskId = data.taskId;
      if (approvals.templateAttachment) {
        formBaseInfo.value.templateAttachment = onInitFileList(
          JSON.parse(approvals.templateAttachment)
        );
      }
    }
    isChargehand.value = formBaseInfo.value.isChargehand;
    let flowObj = {
      actTaskId: approvals?.actTaskId,
      // actTaskId: data.taskId,
      // approvalComments: data.formBaseInfo.remarks,
      // approvalComments: data.formBaseInfo.instanceId
      //   ? ""
      //   : data.formBaseInfo.approvalComments,
      approvalForm: approvals?.approvalForm,
      approvalResult: "1", // 1：同意、0：不同意
      businessId: approvals?.businessId,
      flowId: data.formBaseInfo?.flowId || data.flowId,
      flowTypeCode: data.formBaseInfo?.flowMinType || props.flowType,
      formAttachment: data.formBaseInfo?.flowStartAttachment || [],
      formTmpData: approvals.formTmpData || "", // 启动时可不传
      // id: data.formBaseInfo.id,
      instanceId: data.formBaseInfo?.instanceId || data.instanceId,
      nodeId: approvals.nodeId || "ACT_010", // 启动时传"ACT_010"
      projectManageId:
        data.formBaseInfo?.projectManageId || data.projectManageId,
      projectTmpId: approvals.projectTmpId,
      // remarks: approvals?.remarks,
      saveState: approvals?.saveState, // 保存传0， 提交传1
      templateAttachment: approvals?.templateAttachment, // 项目模板字段, 不进行修改
      tmpTaskId: approvals.tmpTaskId,
      tmpTaskName: approvals.tmpTaskName
    };
    flowFormData.value = {
      ...flowFormData.value,
      ...flowObj
    };
    flowType.value = data.formBaseInfo?.flowMinType || props.flowType;
    currentNode.value = flowTypeObj[flowType.value]?.curNodeName || []; //某一节点的下一流程节点可选
    signNode.value = flowTypeObj[flowType.value]?.signNode || ""; //会签的节点
    if (currentNode.value.length > 0) {
      let index = currentNode.value.indexOf(props.nodeDefId);
      nextJumpToArr.value =
        flowTypeObj[flowType.value]["nextJumpToArr" + index] || [];
    }
    if (nextJumpToArr.value && nextJumpToArr.value.length) {
      nextJumpToId.value = nextJumpToArr.value[0].id;
      formBaseInfo.value.isChargehand = nextJumpToArr.value[0].isChargehand;
    }
    let nodeName = flowTypeObj[flowType.value].nodeName;
    nodeName.forEach(item => {
      steps.value.push({ step: item, title: item });
    });
    flowFormData.value.approvalForm = approvals?.approvalForm;
    defaultFileList.value = approvals.formAttachment
      ? onInitFileList(JSON.parse(approvals.formAttachment))
      : [];
    instanceIdFlow.value = data.formBaseInfo?.instanceId || data.instanceId;
    // props.isEdit && props.instanceId && getStorageTmpData(); // 20230629 去掉B类保存功能 by wancui
    // if (props.source === "self") {
    // 获取流程数据
    const res2 = await postApproveHistory({
      instanceId: instanceIdFlow.value
    });
    if (res2.code === 200) {
      let length = res2.data.length;
      taskIdNotify.value = length && res2.data[length - 1]?.taskId;
    }
    // }
  }
};

// 获取保存的数据
// const getStorageTmpData = async () => {
//   const info = storageLocal.getItem("info");
//   const { nodeDefId, flowId } = props;
//   let params = {
//     nodeId: nodeDefId,
//     taskId: taskIdMain.value,
//     flowId,
//     handlerId: info ? info?.userId : ""
//   };

//   const { code, data } = await postGetStorageTmpData(params);
//   if (code === 200) {
//     if (data?.valueJson) {
//       // const {approvalComments } = JSON.parse(
//       //   data.valueJson
//       // );
//       // defaultFileList.value = onInitFileList(templateAttachment);
//       // flowFormData.value.approvalComments = approvalComments;
//       // flowFormData.value.approvalForm = approvalForm;
//     }
//   }
// };

const handleChange = fileList => {
  defaultFileList.value = fileList;
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return [];
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

// 保存 未启动时，保存调用暂存接口；已启动进入审批后，调用保存接口 saveState = 0
// const handleSave = async () => {
//   clickEvent(
//     "B类项目审批详情",
//     "保存",
//     `${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
//   );
//   props.instanceId ? handleSaveData() : handleStorageFlow();
// };

// 未启动时的保存
// const handleStorageFlow = async () => {
//   try {
//     const name = storageLocal.getItem("projectInfo")?.name;
//     const id = storageLocal.getItem("projectInfo")?.id;
//     const info = storageLocal.getItem("info");
//     let formData = {
//       approvalComments: flowFormData.value.approvalComments,
//       remarks: flowFormData.value.remarks,
//       approvalForm: flowFormData.value.approvalForm,
//       templateAttachment: onFilterFileData(defaultFileList.value)
//     };
//     const option = [
//       {
//         name: "审批意见",
//         content: formData.approvalComments,
//         type: "textarea"
//       },
//       { name: "备注", content: formData.remarks, type: "textarea" }
//     ];
//     const params = {
//       formBaseInfo: {
//         billName: formBaseInfo.value.billName,
//         projectName: name,
//         projectManageId: id,
//         contractName: formBaseInfo.value.contractName,
//         contractId: formBaseInfo.value.contractId,
//         contractNum: formBaseInfo.value.contractNum,
//         partyA: formBaseInfo.value.partyA,
//         directorAName: formBaseInfo.value.directorAName,
//         directorA: formBaseInfo.value.directorA,
//         directorBId: formBaseInfo.value.directorBId,
//         partyB: formBaseInfo.value.partyB,
//         directorBName: formBaseInfo.value.directorBName,
//         remarks: formData.remarks,
//         approvalComments: formData.approvalComments,
//         flowStartAttachmentArr: onFilterFileData(defaultFileList.value),
//         id: formBaseInfo.value.id
//       },
//       formSubMap: {
//         taskId: flowFormData.value.tmpTaskId,
//         flowType: formBaseInfo.value?.flowMinType || props.flowType,
//         assignee: info ? info?.userId : "",
//         opinion: JSON.stringify(option),
//         valueJson: JSON.stringify(formData)
//       },
//       flowFormData: {
//         approvalComments: formData.approvalComments,
//         approvalForm: formData.approvalForm,
//         formAttachment: JSON.stringify(onFilterFileData(defaultFileList.value)),
//         remarks: formData.remarks
//       }
//     };
//     const { code, message } = await storageFlowdata(params);
//     if (code === 200) {
//       NotifMessage.success("保存成功");
//     } else {
//       NotifMessage.error(message);
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// 保存审批数据
// const handleSaveData = async () => {
//   const info = storageLocal.getItem("info");
//   const { nodeDefId, flowId } = props;
//   let formData = {
//     approvalComments: flowFormData.value.approvalComments,
//     remarks: flowFormData.value.remarks,
//     approvalForm: flowFormData.value.approvalForm,
//     templateAttachment: onFilterFileData(defaultFileList.value)
//   };
//   let params = {
//     nodeId: nodeDefId,
//     taskId: taskIdMain.value,
//     flowId,
//     handlerId: info ? info?.userId : "",
//     userId: info ? info?.userId : "",
//     handlerName: info ? info?.name : "",
//     valueJson: JSON.stringify(formData)
//   };
//   try {
//     const { code, message } = await postStorageTmpData(params);
//     if (code === 200) {
//       NotifMessage.success("保存成功");
//     } else {
//       NotifMessage.error(message);
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

//转办
const handleTransfer = async () => {
  dialogVisibleTransferAdd.value = true;
  dialogVisibleType.value = "transfer";
};

const handleSave = async () => {
  const { flowId } = props;
  const params = {
    flowId: flowId,
    nodeId: nodeDefId.value,
    taskId: formBaseInfo.value?.taskId,
    formJson: JSON.stringify({
      ...flowFormData.value,
      formAttachment: defaultFileList.value || []
    })
  };
  if (!flowId) {
    params["billNum"] = formBaseInfo.value?.billNum;
  }
  const { code, message } = await postSaveDraft(params);
  if (code === 200) {
    NotifMessage.success(message);
  } else {
    NotifMessage.error(message);
  }
};

const getFlowFormData = async () => {
  const { data } = await getDraft(
    formBaseInfo.value?.taskId,
    formBaseInfo.value?.billNum
  );
  if (data?.formJson) {
    const formJson = JSON.parse(data.formJson);
    flowFormData.value = formJson;
    defaultFileList.value = formJson.formAttachment;
  }
};

// 提交 saveState = 1
const handleSubmit = async isChargehand => {
  // 最后一个节点不需要选择下一节点处理人,直接取当前登录人
  formBaseInfo.value.isChargehand = isChargehand;
  let nodes = flowTypeObj[flowType.value].nodeId;
  if (nodeDefId.value === nodes[nodes.length - 1]) {
    //最后一个节点不需要选择下一节点处理人
    if (isChargehand === "0") {
      //驳回
      getApproveUserId();
      dialogVisibleLastNode.value = true;
    } else {
      const isValid = await new Promise(resolve =>
        flowFormRef.value.validate(resolve)
      );
      if (!isValid) return;
      emitAddUser();
    }
  } else {
    const isValid = await new Promise(resolve =>
      flowFormRef.value.validate(resolve)
    );
    if (!isValid) return;
    dialogVisibleTransferAdd.value = true;
    dialogVisibleType.value = "submit";
  }
  // const isValid = await new Promise(resolve =>
  //   flowFormRef.value.validate(resolve)
  // );
  // if (!isValid) return;
  // let nodes = flowTypeObj[flowType.value].nodeId;
  // if (
  //   props.nodeDefId === nodes[nodes.length - 1] &&
  //   !currentNode.value.includes(props.nodeDefId)
  // ) {
  //   emitAddUser();
  // } else {
  //   dialogVisibleTransferAdd.value = true;
  //   dialogVisibleType.value = "submit";
  // }
};

//获取某一节点的处理人
const getApproveUserId = async () => {
  const backNode = flowTypeObj[flowType.value].backNode;
  const { code, data } = await getApproveHandlerId(instanceId.value, backNode);
  if (code === 200) {
    approveHandlerId.value = data[0];
  } else {
    NotifMessage.error("获取处理人失败");
  }
};

const showNextJump = parmas => {
  addUserInfo.value = parmas;
  if (dialogVisibleType.value === "submit") {
    //审核通过
    if (currentNode.value.includes(props.nodeDefId)) {
      //当前节点的下一步节点是可选的
      dialogVisibleTransferAdd.value = false;
      dialogVisibleNext.value = true;
    } else {
      emitAddUser();
    }
  } else if (dialogVisibleType.value === "transfer") {
    //转办
    submitTransfer(parmas);
  } else if (dialogVisibleType.value === "inform") {
    //知会
    submitInform(parmas);
  }
};

const handleNextJump = () => {
  dialogVisibleNext.value = false;
  emitAddUser();
};

const emitAddUser = () => {
  dialogVisibleTransferAdd.value = false;
  const { instanceId } = props;
  let baseInfo = {
    billName: formBaseInfo.value.billName,
    projectName: formBaseInfo.value.projectName,
    projectManageId: formBaseInfo.value.projectManageId,
    contractName: formBaseInfo.value.contractName,
    contractId: formBaseInfo.value.contractId,
    contractNum: formBaseInfo.value.contractNum,
    partyA: formBaseInfo.value.partyA,
    directorAName: formBaseInfo.value.directorAName,
    directorA: formBaseInfo.value.directorA,
    directorBId: formBaseInfo.value.directorBId,
    partyB: formBaseInfo.value.partyB,
    directorBName: formBaseInfo.value.directorBName,
    id: formBaseInfo.value.id
  };

  let formData = {
    approvalComments: flowFormData.value.approvalComments,
    remarks: flowFormData.value.remarks,
    approvalForm: flowFormData.value.approvalForm,
    templateAttachment: onFilterFileData(defaultFileList.value)
  };
  instanceId ? toSubmit(baseInfo, formData) : toStart(baseInfo, formData);
};

// 启动
const toStart = async (baseInfo, formData) => {
  let option = [{ name: "备注", content: formData.remarks, type: "textarea" }];
  if (props.nodeDefId !== "ACT_010") {
    option = [
      {
        name: "审批意见",
        content: formData.approvalComments,
        type: "textarea"
      },
      { name: "备注", content: formData.remarks, type: "textarea" }
    ];
  }
  const info = storageLocal.getItem("info");
  let nodes = flowTypeObj[flowType.value].nodeId;
  let nextHandleId =
    props.nodeDefId === nodes[nodes.length - 1]
      ? info?.userId
      : addUserInfo.value?.idList[0]?.id;
  let params = {
    formBaseInfo: {
      ...baseInfo,
      remarks: formData.remarks,
      approvalComments: formData.approvalComments,
      flowStartAttachmentArr: formData.templateAttachment
    },
    flowFormData: {
      ...flowFormData.value,
      remarks: formData.remarks,
      approvalComments: formData.approvalComments,
      formAttachment: JSON.stringify(formData.templateAttachment)
    },
    formSubMap: {
      flowType: formBaseInfo.value?.flowMinType || props.flowType,
      assignee: nextHandleId,
      opinion: JSON.stringify(option),
      valueJson: JSON.stringify(formData),
      isChargehand: formBaseInfo.value.isChargehand || "0"
    }
  };

  try {
    const { code, message } = await flowStart(params);
    if (code === 200) {
      clickEvent(
        "B类设备项目审批详情",
        "提交",
        `流程发起_${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
      );
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
// 审批
const toSubmit = async (baseInfo, formData) => {
  const { nodeDefId, instanceId, flowId } = props;
  const info = storageLocal.getItem("info");
  let nodes = flowTypeObj[flowType.value].nodeId;
  //最后一个节点的下一步处理人为当前操作人
  let nextHandleId =
    props.nodeDefId === nodes[nodes.length - 1]
      ? info?.userId
      : addUserInfo.value?.idList[0]?.id;
  let option = [];
  if (lastNode.value === nodeDefId && formBaseInfo.value.isChargehand === "0") {
    //驳回到指定节点
    const isValid = await new Promise(resolve =>
      rejectFormRef.value.validate(resolve)
    );
    if (!isValid) return;
    option = [
      { name: "reject", content: "#reject#", type: "textarea" },
      {
        name: "驳回意见",
        content: rejectFormData.value.remark,
        type: "textarea"
      }
    ];
    nextHandleId = approveHandlerId.value;
  } else {
    option = [{ name: "备注", content: formData.remarks, type: "textarea" }];
    if (props.nodeDefId !== "ACT_010") {
      option = [
        {
          name: "审批意见",
          content: formData.approvalComments,
          type: "textarea"
        },
        { name: "备注", content: formData.remarks, type: "textarea" }
      ];
    }
  }
  let params = {
    formBaseInfo: {
      // ...baseInfo,
      id: formBaseInfo.value.id,
      acceptUsers: nextHandleId
      // remarks: formData.approvalComments,
      // flowStartAttachment: JSON.stringify(formData.templateAttachment),
      // flowStartAttachmentArr: formData.templateAttachment
    },
    flowFormData: {
      ...flowFormData.value,
      remarks: formData?.approvalComments,
      approvalComments: formData?.remarks,
      formAttachment: JSON.stringify(formData?.templateAttachment)
    },
    formSubMap: {
      flowType: formBaseInfo.value?.flowMinType || props.flowType,
      nodeId: nodeDefId,
      procInstId: instanceId,
      taskId: taskIdMain.value,
      opinion: JSON.stringify(option),
      assignee: nextHandleId,
      isChargehand: formBaseInfo.value.isChargehand || "0",
      specialReject: "0" // ???
    },
    tmpStorage: {
      nodeId: nodeDefId,
      flowId,
      taskId: taskIdMain.value,
      handlerId: nextHandleId,
      userId: info ? info?.userId : "",
      valueJson: formData ? JSON.stringify(formData) : "{}"
    }
  };
  try {
    const { code, message } = await flowSubmit(params);
    if (code === 200) {
      clickEvent(
        "B类项目审批详情",
        "提交",
        `流程审批_${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
      );
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const submitTransfer = async parmas => {
  const info = storageLocal.getItem("info");
  const option = [{ name: "转办", content: "转办协助处理", type: "textarea" }];
  let params = {
    targetAssignee: parmas?.idList[0].id,
    opinion: JSON.stringify(option),
    instanceId: props.instanceId,
    taskId: taskIdMain.value,
    flowId: props.flowId,
    handlerId: info?.userId,
    handlerName: info?.name,
    businessTraParam: {
      id: formBaseInfo.value.id,
      acceptUsers: info?.userId,
      flowType: formBaseInfo.value?.flowMinType || props.flowType
    }
  };
  try {
    const { code, message } = await transfer(params);
    if (code === 200) {
      clickEvent(
        "B类项目审批详情",
        "转办",
        `${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
      );
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//待阅转为已阅
const submitFlowNotifyRead = async () => {
  const info = storageLocal.getItem("info");
  let { instanceId, taskId, readId } = props;
  let params = {
    assignee: info?.userId,
    instanceId,
    taskId,
    id: readId
  };
  try {
    const { code, message } = await flowNotifyRead(params);
    if (code !== 200) {
      message && NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//选择下一步流程节点
const changeNextJump = async id => {
  nextJumpToArr.value.forEach(item => {
    if (item.id === id) {
      formBaseInfo.value.isChargehand = item.isChargehand;
      isChargehand.value = item.isChargehand;
    }
  });
};
//知会
const submitInform = async parmas => {
  const notifys = [];
  const id = parmas?.idList[0].id;
  notifys.push(id);
  let params = {
    assignee: userInfo?.userId,
    instanceId: instanceId.value,
    taskId: taskIdNotify.value,
    notifys: notifys
  };
  try {
    const { code, message } = await flowNotify(params);
    if (code === 200) {
      NotifMessage.success(message);
      dialogVisibleTransferAdd.value = false;
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
// 返回按钮事件
const handleBack = () => {
  router.push("/approval/todo");
};

const handleReject = () => {
  dialogVisible.value = true;
};

// 知会按钮
const inform = () => {
  if (instanceId.value) {
    dialogVisibleTransferAdd.value = true;
    dialogVisibleType.value = "inform";
  } else {
    NotifMessage.info("当前流程还未发起，暂无法知会");
    return;
  }
};
watchEffect(() => {
  if (formBaseInfo.value?.taskId || formBaseInfo.value?.billNum) {
    getFlowFormData();
  }
});
getInitFlowInfo();
if (props.approvalType === "notify") {
  submitFlowNotifyRead();
}
defineExpose({ getInitFlowInfo, isChargehand, taskIdMain, taskIdNotify });
// });
</script>

<style lang="scss" scoped>
.content-detail :deep .el-dialog .form__footer {
  text-align: right;
}
.next-content {
  padding: 10px 20px;
}
.danger {
  background-color: #f56c6c;
  color: #fff;
}
</style>
